
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>

#define DB_NAME 	"ts-3.1.0.db"
#define SOFTWARE_NAME 	"tcp_client"
#define SERVER_ADDR "127.0.0.1"  // 服务器 IP 地址（本地）
#define SERVER_PORT 8080         // 服务器端口

int main(int argc, char **argv)
{
  char *ip = "0.0.0.0";
  int port = 80;

  if (argc < 3) {
    printf("Usage: tcpclient <ip> <port>\n");
    exit(1);
  }
  ip = argv[1];
  port = atoi(argv[2]);
  printf("server:%s %d\n", ip, port);
  int sockfd = socket(AF_INET, SOCK_STREAM, 0);
  if (sockfd < 0) {
      perror("Socket creation failed");
      exit(1);
  }

  struct sockaddr_in server_addr;
  memset(&server_addr, 0, sizeof(server_addr));
  server_addr.sin_family = AF_INET;
  server_addr.sin_port = htons(port);
  if (inet_pton(AF_INET, ip, &server_addr.sin_addr) <= 0) {
      perror("Invalid address or address not supported");
      exit(1);
  }

  if (connect(sockfd, (struct sockaddr *)&server_addr,
        sizeof(server_addr)) < 0) {
      perror("Connection failed");
      exit(1);
  }

  printf("Connected to server %s:%d\n", SERVER_ADDR, SERVER_PORT);

  char *message = "Hello from TCP client!";
  if (send(sockfd, message, strlen(message), 0) < 0) {
      perror("Send failed");
      exit(1);
  }
  printf("Message sent: %s\n", message);

  char buffer[1024];
  int n = recv(sockfd, buffer, sizeof(buffer) - 1, 0);
  if (n < 0) {
      perror("Receive failed");
      exit(1);
  }
  buffer[n] = '\0';  // 确保字符串结束
  printf("Received from server: %s\n", buffer);

  close(sockfd);
  return 0;
}
